const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
const PORT = 3000;

// 连接MongoDB数据库
mongoose.connect('mongodb://localhost:27017/warehouse', {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB连接错误:'));
db.once('open', () => {
  console.log('MongoDB连接成功');
});
// 配置中间件
app.use(cors());
app.use(bodyParser.json());

// 定义商品信息模型
const productSchema = new mongoose.Schema({
  productId: { type: String, required: true, unique: true },
  name: { type: String, required: true },
  model: { type: String, required: true },
  price: { type: Number, required: true },
  stockIn: { type: Number, default: 0 },
  stockInTime: { type: Date, default: Date.now },
  stockOut: { type: Number, default: 0 },
  stockOutTime: { type: Date }
});

const Product = mongoose.model('Product', productSchema);
// 导出 Excel
const ExcelJS = require('exceljs');
const path = require('path');
app.get('/api/products/export/excel', async (req, res) => {
  try {
    // 获取汇总数据
    const summary = await Product.aggregate([
      {
        $project: {
          productId: 1,
          name: 1,
          model: 1,
          price: 1,
          inventory: { $subtract: ['$stockIn', '$stockOut'] }
        }
      }
    ]);

    if (summary.length === 0) {
      return res.status(400).json({ error: '没有数据可导出' });
    }

    // 创建 Excel 工作簿和工作表
    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet('库存汇总');

    // 添加表头
    worksheet.columns = [
      { header: '商品编号', key: 'productId', width: 15 },
      { header: '名称', key: 'name', width: 20 },
      { header: '型号', key: 'model', width: 20 },
      { header: '单价', key: 'price', width: 10 },
      { header: '库存', key: 'inventory', width: 10 }
    ];

    // 添加数据行
    summary.forEach((item) => {
      worksheet.addRow(item);
    });

    // 设置响应头
    res.setHeader(
      'Content-Type',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    );
    res.setHeader(
      'Content-Disposition',
      `attachment; filename*=UTF-8''${encodeURIComponent('库存汇总表.xlsx')}`
    );

    // 写入并发送文件
    await workbook.xlsx.write(res);
    res.end();
  } catch (error) {
    console.error('导出 Excel 失败:', error);
    res.status(500).json({ error: '导出 Excel 失败', details: error.message });
  }
});

// 导出 PDF
const PDFDocument = require('pdfkit');
const blobStream = require('blob-stream');

app.get('/api/products/export/pdf', async (req, res) => {
  try {
    // 获取汇总数据
    const summary = await Product.aggregate([
      {
        $project: {
          productId: 1,
          name: 1,
          model: 1,
          price: 1,
          inventory: { $subtract: ['$stockIn', '$stockOut'] }
        }
      }
    ]);

    if (summary.length === 0) {
      return res.status(400).json({ error: '没有数据可导出' });
    }

    // 设置响应头
    res.setHeader('Content-Type', 'application/pdf');
    res.setHeader(
      'Content-Disposition',
      `attachment; filename*=UTF-8''${encodeURIComponent('库存汇总表.pdf')}`
    );

    // 创建 PDF 文档
    const doc = new PDFDocument({ size: 'A4', margin: 50 });
    const stream = doc.pipe(res); // 直接将 PDF 流输出到响应
    doc.font('fonts/SimHei.ttf');

    // 添加标题
    doc.fontSize(20).text('库存汇总表', { align: 'center' });
    doc.moveDown();

    // 添加日期
    doc.fontSize(14).text(new Date().toLocaleDateString(), { align: 'center' });
    doc.moveDown(2);

    // 定义表格样式和位置
    const tableTop = doc.y;
    const columnCount = 5;
    const columnWidth = (doc.page.width - doc.page.margins.left - doc.page.margins.right) / columnCount;

    // 表格标题行
    const headers = ['商品编号', '名称', '型号', '单价', '库存'];

    // 绘制表头
    doc.font('fonts/SimHei.ttf').fontSize(12);

    headers.forEach((header, index) => {
      doc.text(header, doc.page.margins.left + index * columnWidth, tableTop);
    });

    // 绘制表格内容
    const rowHeight = 25;
    doc.font('fonts/SimHei.ttf').fontSize(10);

    summary.forEach((item, rowIndex) => {
      const y = tableTop + (rowIndex + 1) * rowHeight;

      // 绘制数据行
      const rowData = [
        item.productId,
        item.name,
        item.model,
        `¥${item.price.toFixed(2)}`,
        item.inventory
      ];

      rowData.forEach((cell, colIndex) => {
        doc.text(cell.toString(), doc.page.margins.left + colIndex * columnWidth, y);
      });

      // 绘制分隔线
      doc.moveTo(doc.page.margins.left, y )
        .lineTo(doc.page.width - doc.page.margins.right, y )
        .stroke();
    });

    // 绘制表格边框
    const tableBottom = tableTop + (summary.length + 1) * rowHeight;
    const tableLeft = doc.page.margins.left;
    const tableRight = doc.page.width - doc.page.margins.right;

    // 上下边框
    doc.moveTo(tableLeft, tableTop).lineTo(tableRight, tableTop).stroke();
    doc.moveTo(tableLeft, tableBottom).lineTo(tableRight, tableBottom).stroke();

    // 垂直边框
    for (let i = 0; i <= columnCount; i++) {
      const x = tableLeft + i * columnWidth;
      doc.moveTo(x, tableTop).lineTo(x, tableBottom).stroke();
    }

    // 完成并发送 PDF
    doc.end();

  } catch (error) {
    console.error('导出 PDF 失败:', error);
    res.status(500).json({ error: '导出 PDF 失败', details: error.message });
  }
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`);
});

